package com.centon.auto_code.project.service.impl;

import com.centon.auto_code.comm.ServiceCode;
import com.centon.auto_code.domain.ProProject;
import com.centon.auto_code.domain.ProProjectDatabaseRel;
import com.centon.auto_code.domain.ProTable;
import com.centon.auto_code.domain.gen.ProProjectDatabaseRelCriteria;
import com.centon.auto_code.domain.gen.ProTableCriteria;
import com.centon.auto_code.mapper.ProProjectDatabaseRelMapper;
import com.centon.auto_code.mapper.ProProjectMapper;
import com.centon.auto_code.mapper.ProTableMapper;
import com.centon.auto_code.project.service.ProTableService;
import com.centon.auto_code.project.vo.ProTableVo;
import com.centon.auto_code.util.BeanUtil;
import com.centon.auto_code.vo.BaseRes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProTableServiceImpl implements ProTableService {


    @Autowired
    private ProTableMapper proTableMapper;

    @Autowired
    private ProProjectDatabaseRelMapper proProjectDatabaseRelMapper;

    @Autowired
    private ProProjectMapper proProjectMapper;

    @Override
    public BaseRes<List<ProTableVo>> queryTable(ProTableVo proTableVo) {

        BaseRes<List<ProTableVo>> res = new BaseRes<>();


        // 1、获取所关联数据库
        ProProjectDatabaseRelCriteria mProProjectDatabaseRelCriteria = new ProProjectDatabaseRelCriteria();
        mProProjectDatabaseRelCriteria.createCriteria().andProjectIdEqualTo(proTableVo.getProjectId());
        List<ProProjectDatabaseRel> dbs = proProjectDatabaseRelMapper.selectByExample(mProProjectDatabaseRelCriteria);

        // 2、获取数据库关联表
        if (dbs.size() > 0) {
            List<String> ids = new ArrayList<>();
            for (ProProjectDatabaseRel db : dbs) {
                ids.add(db.getDatabaseId());
            }

            ProTableCriteria mProTableCriteria = new ProTableCriteria();
            mProTableCriteria.createCriteria().andDatabaseIdIn(ids);
            List<ProTable> tables = proTableMapper.selectByExample(mProTableCriteria);

            if (tables.size() > 0) {
                List<ProTableVo> tabVos = BeanUtil.voConvertList(tables, ProTableVo.class);
                if ("vo".equalsIgnoreCase(proTableVo.getFrom())) {
                    ProProject proProject = proProjectMapper.selectByPrimaryKey(proTableVo.getProjectId());
                    String ignoreTables = proProject.getIgnoreTables(); // 忽略生成表

                    tabVos = tabVos.stream().filter(table -> ignoreTables.indexOf("\"" + table.getId() + "\"") < 0)
                            .collect(Collectors.toList());
                }
                res.setData(tabVos);
            }
        }

        res.setServiceCode(ServiceCode.SUCCESS);
        return res;
    }
}
